import * as vscode from "vscode";
import { addComment } from "../plugins/actions/AddComment/addComment";
import { optimizeCode } from "../plugins/actions/OptimizeCode/optimizeCode";
import { VerticalDiffManager } from "./diff/vertical/manager";
import { LLMFactory } from "../core/llm/llmFactory";
import { HarmonyPilotGUIWebviewViewProvider } from "./HarmonyPilotGUIWebviewViewProvider";
import { focusInput } from "../plugins/actions/FocusInput/focusInput";
import { CommentCollectionFactory, CommentCollectionType } from "../core/comments/CommentCollectionFactory";
import { aiReview } from "../plugins/actions/AiReview/aiReview";
import { HarmonyPilotCommentCollectionProvider } from "../core/comments/HarmonyPilotCommentCollectionProvider";
import { singleFileApiChange, allFileApiChange, actApiPilotCommand } from "../plugins/actions/ApiPilot/ApiPilot";

import * as os from "os";
import * as path from "path";
import * as fs from "fs";
import { LoginService } from "./services/loginService";
import { docLinter } from "../plugins/actions/DocLinter/docLinter";
import { DocLinterGUIWebviewViewProvider } from "./DocLinterGUIWebviewViewProvider";
import { generateUnitTest } from "../plugins/actions/UnitTest/unitTest";

/**
 * 打开MCP配置文件
 */
async function openMcpConfigFile() {
  try {
    // 获取用户主目录
    const homeDir = os.homedir();
    const mcpJsonPath = path.join(homeDir, '.harmonypilot', 'mcp.json');
    
    // 检查文件是否存在
    if (!fs.existsSync(mcpJsonPath)) {
      // 如果不存在，创建目录和默认配置文件
      const harmonyPilotDir = path.join(homeDir, '.harmonypilot');
      if (!fs.existsSync(harmonyPilotDir)) {
        fs.mkdirSync(harmonyPilotDir, { recursive: true });
      }
      
      // 默认配置
      const defaultConfig = {
        mcpServers: {}
      };
      
      fs.writeFileSync(mcpJsonPath, JSON.stringify(defaultConfig, null, 2), 'utf-8');
    }
    
    // 打开文件
    const document = await vscode.workspace.openTextDocument(mcpJsonPath);
    await vscode.window.showTextDocument(document);
    
    // 显示提示
    vscode.window.showInformationMessage('修改MCP配置后保存，更改将自动应用到插件中');
  } catch (error) {
    console.error('打开MCP配置文件失败:', error);
    vscode.window.showErrorMessage(`无法打开MCP配置文件: ${error}`);
  }
}

// Copy everything over from extension.ts
const getCommandsMap: (verticalDiffManager: VerticalDiffManager, llmFactory: LLMFactory, 
    sidebar: HarmonyPilotGUIWebviewViewProvider, docLinterSidebar: DocLinterGUIWebviewViewProvider, commentCollectionFactory: CommentCollectionFactory, context: vscode.ExtensionContext) 
=> { [command: string]: (...args: any) => any } = 
(verticalDiffManager: VerticalDiffManager, llmFactory: LLMFactory, sidebar: HarmonyPilotGUIWebviewViewProvider, docLinterSidebar: DocLinterGUIWebviewViewProvider, commentCollectionFactory: CommentCollectionFactory, context: vscode.ExtensionContext) => {
    return {
        // Toggle View
        "HarmonyPilot.toggleView": async () => {
            sidebar.toggleDocLinterView();
        },

        // Login
        "HarmonyPilot.login": async () => {
            LoginService.getInstance(context).startLogin();
        },

        // Logout
        "HarmonyPilot.logout": async () => {
            LoginService.getInstance(context).logout();
        },

        // DocLinter    
        "HarmonyPilot.docLinter": async (...args) => {
            await vscode.commands.executeCommand("HarmonyPilot.docLinterGUIView.focus");
            docLinter(context, docLinterSidebar.getWebview(), ...args);
        },

        // Focus Input
        "HarmonyPilot.focusInput": async () => {
            focusInput(sidebar);
        },

        "HarmonyPilot.newChatBtnClick": async () => {
            //TODO: 实现New Chat命令
        },

        "HarmonyPilot.chatHistoryBtnClick": async () => {
            //TODO: 实现Chat History命令
        },

        "HarmonyPilot.helpBtnClick": async () => {
            //TODO: 实现Help命令
        }, 

        "HarmonyPilot.issueReportBtnClick": async () => {
            //TODO: 实现Issue Report命令
        },

        "HarmonyPilot.settingBtnClick": async () => {   
            try {
                // 获取用户主目录下的 .harmonypilot/mcp.json 文件路径
                const homeDir = os.homedir();
                const mcpJsonPath = path.join(homeDir, '.harmonypilot', 'mcp.json');
                
                // 检查文件是否存在
                if (fs.existsSync(mcpJsonPath)) {
                    // 使用 VSCode 打开文件
                    const document = await vscode.workspace.openTextDocument(mcpJsonPath);
                    await vscode.window.showTextDocument(document);
                } else {
                    vscode.window.showErrorMessage('配置文件不存在，请重新启动 VSCode');
                }
            } catch (error) {
                console.error('打开配置文件失败:', error);
                vscode.window.showErrorMessage(`打开配置文件失败: ${error}`);
            }
        },
        "HarmonyPilot.rejectVerticalDiffBlock": async(fileUri?: string, index?: number) => {
            verticalDiffManager.acceptRejectVerticalDiffBlock(false, fileUri, index);
        }, 

        "HarmonyPilot.acceptVerticalDiffBlock": async(fileUri?: string, index?: number) => {
            verticalDiffManager.acceptRejectVerticalDiffBlock(true, fileUri, index);
        },
    
        // Write Comment for Code
        "HarmonyPilot.writeCommentForCode": async () => {   
            addComment(verticalDiffManager, llmFactory, context);
        },
        
        // Optimize Code
        "HarmonyPilot.optimizeCode": async () => {
            optimizeCode(verticalDiffManager, llmFactory, context);
        },

        // Generate Unit Test
        "HarmonyPilot.generateUnitTest": async () => {
            generateUnitTest(verticalDiffManager, llmFactory, context);
        },
        "HarmonyPilot.apiPilotSingleFileCheck": async () => {
            // 单文件API检查
            singleFileApiChange();
        },
        "HarmonyPilot.apiPilotAllFileCheck": async () => {
            // 全文件API检查
            allFileApiChange();
        },

        // Apply And Go To Next
        'harmonypilot.applyAndGoToNext': (threadUuid: string) => {
                const collection = HarmonyPilotCommentCollectionProvider.getCollection(threadUuid);
                if (collection == undefined) {
                    return;
                }
                collection.applyAndGoToNext(threadUuid);
        },

        // Discard And Go To Next
        'harmonypilot.discardAndGoToNext': (threadUuid: string) => {
            const collection = HarmonyPilotCommentCollectionProvider.getCollection(threadUuid);
            if (collection == undefined) {
                return;
            }
            collection.discardAndGoToNext(threadUuid);
        },

        // Go To Next
        'harmonypilot.goToNextByTitle': (thread: vscode.CommentThread) => {
            const uuid = HarmonyPilotCommentCollectionProvider.getUuidByThread(thread);
            if (uuid == undefined) {
                return;
            }
            const collection = HarmonyPilotCommentCollectionProvider.getCollection(uuid);
            if (collection == undefined) {
                return;
            }
            collection.goToNextComment(uuid);
        },

        // Go To Previous
        'harmonypilot.goToPreviousByTitle': (thread: vscode.CommentThread) => {
            const uuid = HarmonyPilotCommentCollectionProvider.getUuidByThread(thread);
            if (uuid == undefined) {
                return;
            }
            const collection = HarmonyPilotCommentCollectionProvider.getCollection(uuid);
            if (collection == undefined) {
                return;
            }
            collection.goToPreviousComment(uuid);
        },

        // AI Review
        "HarmonyPilot.aiReview": async () => {
            const commentCollection = commentCollectionFactory.getCommentCollection(CommentCollectionType.AI_REVIEW);
            if (!commentCollection) {
                vscode.window.showErrorMessage("AI Review comment collection not found");
                return;
            }
            // 必须要做
            commentCollection.clear();
            aiReview(commentCollection, llmFactory, context);
        },

        // Open MCP Config
        "HarmonyPilot.openMcpConfig": openMcpConfigFile
    };
};

export function registerAllCommands(
    context: vscode.ExtensionContext,
    verticalDiffManager: VerticalDiffManager,
    llmFactory: LLMFactory,
    sidebar: HarmonyPilotGUIWebviewViewProvider,
    docLinterSidebar: DocLinterGUIWebviewViewProvider,
    commentCollectionFactory: CommentCollectionFactory
) {
    for (const [command, callback] of Object.entries(
        getCommandsMap(verticalDiffManager, llmFactory, sidebar, docLinterSidebar, commentCollectionFactory, context)
    )) {
        // 注册所有命令
        context.subscriptions.push(
            vscode.commands.registerCommand(command, callback),
        );
    }
    // 注册API Pilot命令
    actApiPilotCommand(context, verticalDiffManager, llmFactory);
}
